
import SwiftUI

struct FactorySelectionView: View {
    @EnvironmentObject var appState: AppState
    @Environment(\.openImmersiveSpace) var openImmersiveSpace
    @Environment(\.dismissImmersiveSpace) var dismissImmersiveSpace

    // 定义两列网格布局
    let columns: [GridItem] = [
        GridItem(.flexible(), spacing: 20),
        GridItem(.flexible(), spacing: 20)
    ]

    var body: some View {
        VStack(spacing: 30) {
            Text("选择工厂")
                .font(.title)

            LazyVGrid(columns: columns, spacing: 20) {
                ForEach(appState.factoryNames, id: \.self) { name in
                    Button(name) {
                        // 1. 设置状态
                        appState.selectFactory(name)

                        // 2. 异步打开沉浸式空间
                        Task {
                            // 先尝试关闭任何已打开的同 ID 空间（虽然通常不需要）
                            await dismissImmersiveSpace()
                            appState.isImmersiveSpaceShown = false

                            // 打开新的空间
                            let result = await openImmersiveSpace(id: appState.immersiveSpaceID)
                             if case .opened = result {
                                 appState.isImmersiveSpaceShown = true
                                // 可选：关闭当前的选择窗口
                                // dismissWindow(id: "main-window")
                             } else {
                                print("Error opening immersive space for factory \(name)")
                                 appState.currentModelType = .none // 打开失败则重置
                             }
                        }
                    }
                    .buttonStyle(.borderedProminent) // 或其他样式
                    .controlSize(.large)
                }
            }

            Button("返回主菜单") {
                appState.currentScreen = .mainMenu
            }
            .padding(.top, 20)
        }
        .padding(40)
       // .glassBackgroundEffect()
    }
}
